﻿using System.Xml.Linq;
using FarseerGames.FarseerPhysics.Mathematics;
using FreeGoo.GameEngine;
using FreeGoo.GameEngine.Renderables;

namespace FreeGoo.LevelClasses.LevelParts
{
    public abstract class RenderableLevelPart : LevelPart
    {
        public abstract Renderable BuildRenderable(Level level, XElement element);

        public override void AddToEngineFromXml(Level level, XElement element)
        {
            Renderable renderable = BuildRenderable(level, element);
            renderable.Identifier = element.Attribute("Identifier") == null ? null : element.Attribute("Identifier").Value;
            UpdateGraphics(level, element.Element("Graphics"), renderable);
            UpdateBehaviors(level, element.Element("Behaviors"), renderable);
        }

        private void UpdateBehaviors(Level level, XElement element, Renderable renderable)
        {
            if (element == null)
            {
                return;
            }

            foreach (XElement behaviorElement in element.Elements())
            {
                AddBehavior(level, renderable, behaviorElement);
            }
        }

        private void AddBehavior(Level level, Renderable renderable, XElement behaviorElement)
        {
            level.AddBehaviorToRenderable(renderable, this, behaviorElement);
        }

        private void UpdateGraphics(Level level, XElement element, Renderable renderable)
        {
            if (element == null)
            {
                return;
            }

            // <Graphics ImageName="BlueBox90x30.bmp" Offset="-10,-10" />
            GraphicsArgument graphicsArgument = new GraphicsArgument
            {
                ImageName = level.LevelRelativeFileName(element.Attribute("ImageName").Value),
                Offset = element.Attribute("Offset").ToVector2(new Vector2(0, 0)),
            };

            renderable.Engine.RendererFactory.UpdateRenderer(renderable, graphicsArgument);
        }
    }
}
